const router = require('koa-router')()


/*
  留言接口
*/

router

// 获取留言列表
.post('/getGuestList', async (ctx, next) => {
  let query = ctx.request.body

  console.log(query)
  // 设置查询对象
  let selectOption = {}
  
  try {
    if(query.name !== '') selectOption['guestName'] =  { $regex: query.name}
    if(query.date !== ('' || null) ) selectOption['createTime'] = { $gt:query.date[0],$lt: query.date[1]}
    if(query.isReply !== '') selectOption['isReply'] = query.isReply
    
    let result = await ctx.db.GuestBook.find({...selectOption})
    .skip((query.currentPage-1) * query.pageSize)
    .limit(query.pageSize)
    .sort('-createTime')
    .exec()

    let counts = await ctx.db.GuestBook.find({...selectOption}).countDocuments().exec()
    ctx.body = {
      code: 0,
      message: '获取留言列表成功',
      data: {
        guestList: result,
        counts: counts
      }
    }
  } catch (error) {
    console.error(error.message)
    ctx.body = { code: 1, message: error.message, data: null }
  }
})

// 回复留言
.post('/updateGuestReply', async (ctx, next) => {
  let query = ctx.request.body
  console.log(query)
  try {
    let result = await ctx.db.GuestBook.updateOne({
      _id: query._id
    }, {
      reply: query.reply,
      isReply: true
    })
    ctx.body = { code: 0, message: '修改成功', data: result }
  } catch (error) {
    console.log(error.message)
    ctx.body = { code: 1, message: error.message, data: null }
  }
})

// 删除留言
.get('/deleteGuest', async (ctx, next) => {
  let {id} = ctx.query
  try {
    let result = await ctx.db.GuestBook.deleteOne({
      _id: id
    })
    ctx.body = { code: 0, message: '删除留言成功', data: result }
  } catch (error) {
    console.log(error.message)
    ctx.body = { code: 1, message: error.message, data: null }
  }
})

module.exports = router